<template>
	<view class="page">
		
		<s-navbar ref="hxnb" :config="config">
			<view slot="left" style="height: 100%;">
				<view class="address flex align-center padding-left-sm">
					<text>{{address}}</text>
				</view>
			</view>
		</s-navbar>
		
		<swiper :indicator-dots="false" :autoplay="false" :interval="3000" :duration="1000" :circular="true" class="swiper"
			:current="current" @change="changeBanner">
			<swiper-item v-for="(item,index) in bannerList" :key="index">
				<view class="swiper-item">
				<!-- <view class="swiper-item" :style="{'background-image':`url(${$wanlshop.oss(item.media)})`}"> -->
					<image :src="$wanlshop.oss(item.media)" class="swiperImg" mode="scaleToFill"></image>
				</view>
			</swiper-item>
		</swiper>
		<view class="news" v-if="list.length > 0">
			<s-news :list="list"></s-news>
		</view>
		
		<view class="skeleton">
			<s-skeleton type="info" :loading="loading3"></s-skeleton>
		</view>
		<view class="store-box" v-if="storeList">
			<view class="item-box" v-for="(store,i) in storeList" :key="i" @tap="chooseStore(store)">
				<view class="container top-box">
					<view class="left">
						<image src="/static/restaurant/common/store.png" mode="widthFix"></image>
					</view>
					<view class="right">

						<text class="tit">{{store.name}}（{{store.store_type_text}}）</text>
						<view class="row justify-content">
							<view class="row-left">
								<text class="t1" v-if="store.shop_status > 1">{{store.shop_status == 2 ? '暂停营业' : store.shop_status == 3 ? '停止营业' : ''}}</text>
								<text class="t2">销量 {{store.sale}}</text>
							</view>
							<view class="row-right" v-if="store.distance">
								<i class="hxicon-locationfill"></i>
								<text>{{store.distance}}</text>
							</view>
						</view>
						<view class="row">
							<!-- <text>起送￥{{store.starting_price}}</text>
							<text class="t2" v-if="store.shipping_dees > 0">配送￥{{store.shipping_dees}} </text>
							<text class="t2" v-else>免费配送</text> -->
							<text>营业时间：{{store.business_hours}}</text>
						</view>
						<!-- <view class="row">
							
						</view> -->
					</view>
				</view>
				<scroll-view scroll-x class="bottom-box">
					<view class="bottom-box-container">
						<view class="goods-box" v-for="(goods,j) in store.goods" :key="j">
							<view class="img-box">
								<image :src="$wanlshop.oss(goods.image)" mode="aspectFill"></image>
								<!-- <view class="tag">
									{{goods.tag}}
								</view> -->
							</view>
							<view class="tit">
								{{goods.title}}
							</view>
							<view class="price-box">
								<text class="txt1">￥</text>
								<text class="txt2">{{goods.price}}</text>
								<!-- <text class="txt3">￥{{goods.price}}</text> -->
							</view>
						</view>
					</view>

				</scroll-view>
			</view>
		</view>
		<s-empty v-else></s-empty>

		<s-coupon-popup ref="coupon_pop" content="优惠劵" :theme="theme" title="恭喜你" :coupon="coupon"
			@getClick="handleGetClick"></s-coupon-popup>
	</view>
</template>

<script>
	var QQMapWX = require("@/common/qqmap-wx-jssdk.js");
	var qqmapsdk;
	import {
		mapState
	} from 'vuex';
	export default {
		data() {
			return {
				config:{
					title: "",
					leftSlot:true,
					back:false,
					backgroundColor:'transparent',
					backgroundImg: ''
				},
				loading3: true,
				list:[],
				address: "获取定位中",
				latitude: '',
				longitude: '',
				current: 0,
				bannerList: [],
				pageScrollTop: 0, // 页面滚动距离
				opacity: 0,
				headColor: '#fff',
				coupon: null,
				theme: Math.floor(Math.random() * 2) + 1,
				storeList: []
			}
		},
		computed: {
			...mapState(['user', 'common']),
			// topNav() {
			// 	this.opacity = this.pageScrollTop / 150; // 数值越大，背景变化的时间越长
			// }
		},
		// 页面滚动监听
		// onPageScroll(e) {
		// 	this.pageScrollTop = Math.floor(e.scrollTop);
		// 	if (e.scrollTop <= 90) {
		// 		uni.setNavigationBarColor({
		// 			frontColor: '#ffffff',
		// 			backgroundColor: '#ffffff',
		// 			animation: {
		// 				duration: 1
		// 			}
		// 		})
		// 		this.headColor = '#fff'
		// 	} else if (e.scrollTop > 90) {
		// 		uni.setNavigationBarColor({
		// 			frontColor: '#000000',
		// 			backgroundColor: '#ffffff',
		// 			animation: {
		// 				duration: 1
		// 			}
		// 		})
		// 		this.headColor = '#000'
		// 	}
		// },
		onLoad() {
			this.getNotice()
			this.getAdvert()
			if (this.user.isLogin) {
				this.iswindow()
			}
		},
		onShow() {
			this.getLocalAuthorize()
		},
		methods: {
			changeBanner(e) {
				this.current = e.detail.current
				this.config.backgroundImg = this.$wanlshop.oss(this.bannerList[this.current].media)
				this.$refs.hxnb.init()
			},
			async getNotice() {
				let res = await this.$api.getNotice({
					list_rows:100
				});
				if (res.code == 1) {
					this.list = res.data.data
				}
			},
			async chooseStore(item) {
				this.$store.dispatch('common/setStore', item);
				let res = await this.$api.getStore({
					storeid: item.id
				});
				if (res.code == 1) {
					if(res.data.content) {
						res.data.content = res.data.content.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/gi, (
							match, capture) => {
							var img =
								`<img style="display: block; max-width: 100%;" src="${this.$wanlshop.oss(capture)}">`;
							return img;
						});
					}
					this.$store.dispatch('common/setStore', res.data);
					this.$wanlshop.auth(`/pages/restaurant/index`)
				}
			},
			getLocalAuthorize() {
				let that = this
				// 判断是否有位置权限
				
				// #ifdef H5
				that.getLocation()	
				// #endif
				// #ifdef MP-WEIXIN
				uni.getSetting({
				  success(res) {
				    if (!res.authSetting['scope.userFuzzyLocation']) {
				      // 没有位置权限
				      uni.authorize({
				        scope: 'scope.userFuzzyLocation',
				        success() {
				          // 用户已授权，可以直接调用 getFuzzyLocation
				          uni.getFuzzyLocation({
				            success: function (res) {
				              console.log('获取位置成功', res);
											that.getLocation()
				            },
				            fail: function (err) {
				              console.log('获取位置失败', err);
				            }
				          });
				        },
				        fail() {
				          // 用户拒绝授权，可引导用户去设置中开启
				          uni.showModal({
				            title: '提示',
				            content: '此功能需要获取您的位置信息，请确认授权',
				            success: function (modalRes) {
				              if (modalRes.confirm) {
				                uni.openSetting();
				              } else {
												that.loadData()
											}
				            }
				          });
				        }
				      });
				    } else {
				      // 已有位置权限，可以直接调用 getFuzzyLocation
				      that.getLocation()
				    }
				  }
				});
				// #endif
			},
			// 获取当前市区定位
			getLocation() {
				let that = this
				// #ifdef MP-WEIXIN
				uni.getFuzzyLocation({
					type: 'wgs84',
					success(res) {
						//填入自己的key
						qqmapsdk = new QQMapWX({
								key: "JTEBZ-O6Z6W-YCQR6-OEV3F-LICME-EKBRK"
							}),
							that.latitude = res.latitude;
						that.longitude = res.longitude;
						that.loadData()
						//wx.getFuzzyLocation()方法获取的只是所在地区的经纬度，
						//获取所在地区的具体城市信息还需要进行逆地址解析
						qqmapsdk.reverseGeocoder({
							location: {
								latitude: that.latitude,
								longitude: that.longitude
							},
							success: function(res) {
								// console.log(res)
								that.address = res.result.address;
							},
							fail: function(err) {
								console.log(err);
							},
						})
					}
				})
				// #endif
				// #ifdef H5
				uni.getLocation({
					type: 'gcj02',
					geocode: true,
					success(res) {
						that.latitude = res.latitude;
						that.longitude = res.longitude;
						that.loadData()
						uni.request({
							url: that.$config.baseUrl + '/index/getlocation',
							 // url: 'https://restapi.amap.com/v3/geocode/regeo',
							data: {
								key: 'BVCBZ-C4M6B-GYWUK-N7BAL-H4PUE-VYFNF',
								location: res.latitude + ',' + res.longitude
							},
							success: res => {
								if (res.statusCode == 200) {
									that.address = JSON.parse(res.data.data).result.address
								}
							}
						});
					},
					fail: (e) => {
						console.log(e)
					}
				})
				// #endif
			},
			async iswindow() {
				let res = await this.$api.iswindow();
				if (res.code == 1 && res.data && res.data.isshow == 1) {
					this.coupon = res.data.data
					this.$nextTick(() => {
						this.$refs.coupon_pop.show = true
					})
				}
			},
			handleGetClick() {
				this.$refs.coupon_pop.show = false
				this.$wanlshop.auth('/pages/restaurant/user/coupons/coupons')
			},
			async addCarStorage(data) {
				let res = await this.$api.addCarStorage({
					type: 'add',
					data: {
						goods_id: data.id,
						number: 1
					}
				});
				if (res.code == 1) {
					this.$wanlshop.auth('/pages/restaurant/index/shopping?t=2')
				}
			},
			async getAdvert() {
				let res = await this.$api.getAdvert({
					module: 'index'
				});
				if (res.code == 1) {
					this.bannerList = res.data;
					this.config.backgroundImg = this.$wanlshop.oss(this.bannerList[this.current].media)
					this.$refs.hxnb.init()
				}
			},
			async loadData() {
				let res = await this.$api.getIndex({
					lat:this.latitude,
					lng:this.longitude
				});
				if (res.code == 1) {
					this.storeList = res.data;
					this.loading3 = false
				}
			}
		}
	}
</script>

<style lang="less" scoped>
	.address {
		width: 100%;
		height: 100%;
		text {
			font-size: 32rpx;
		}
	}
	.swiper {
		width: 100%;
		height: 500rpx;
		position: relative;

		.swiper-item {
			width: 100%;
			height: 100%;
			background-repeat: no-repeat;
			background-size: 100%;
			.swiperImg {
				width: 100%;
				height: 100%;
			}
		}
	}

	.content {
		width: 100% !important;
		display: flex;
		align-items: center;
		text-align: left;
		padding: 0 220rpx 0 30rpx;
	}

	.store-box {
		margin-top: 20rpx;

		.item-box {
			background-color: #ffffff;
			display: flex;
			flex-direction: column;
			margin-bottom: 20rpx;
			box-sizing: border-box;
			padding: 30rpx;

			.top-box {
				display: flex;
				flex-direction: row;

				.left {
					margin-right: 20rpx;

					image {
						width: 70rpx;
						height: 70rpx;
					}
				}

				.right {
					flex: 1;

					.tit {
						font-size: 32rpx;
						font-weight: bold;
						color: #333333;
						white-space: nowrap;
						overflow: hidden;
						text-overflow: ellipsis;
					}

					.justify-content {
						display: flex;
						flex-direction: row;
						justify-content: space-between;
					}

					.row {
						font-size: 24rpx;
						color: #999999;
						margin-top: 4rpx;

						.row-left {
							display: flex;
							flex-direction: row;

							.t1 {
								background-color: #999999;
								color: #fff;
								font-size: 22rpx;
								padding: 2rpx 10rpx;
								border-radius: 6rpx;
							}

						}

						.t1 {
							margin-right: 12rpx;
						}

						.row-right {
							display: flex;
							flex-direction: row;

							i {
								margin-right: 4rpx;
							}
						}

					}
				}
			}

			.bottom-box {
				&-container {
					// margin: 12px 0 0;
					padding-left: 90rpx;
					
					white-space: nowrap;

					.goods-box {
						width: 190rpx;
						margin-right: 20rpx;
						margin-top: 20rpx;
						display: inline-block;
						.img-box {
							position: relative;
							width: 190rpx;
							height: 190rpx;
							border-radius: 10rpx;

							image {
								width: 190rpx;
								height: 190rpx;
								border-radius: 10rpx;
							}

							.tag {
								position: absolute;
								bottom: 0;
								left: 0;
								background-color: #FF5722;
								color: #ffffff;
								padding: 2rpx 4rpx;
								font-size: 12rpx;
								border-radius: 4rpx;
							}
						}

						.tit {
							font-size: 28rpx;
							margin-top: 6rpx;
							white-space: nowrap;
							overflow: hidden;
							text-overflow: ellipsis;
						}

						.price-box {
							margin-top: 4rpx;

							.txt1 {
								font-size: 26rpx;
								color: #FF5722;
							}

							.txt2 {
								font-size: 28rpx;
								color: #FF5722;
							}

							.txt3 {
								margin-left: 6rpx;
								font-size: 28rpx;
								color: #bbbbbb;
								text-decoration: line-through;
							}
						}
					}

					.goods-box:last-child {
						margin-right: 12rpx;
					}

				}

			}
		}

		.item-box:last-child {
			border-bottom: 0;
		}
	}

	.nav {
		width: 100%;
		height: auto;
		position: fixed;
		z-index: 999;
		top: 0;
		left: 0;
		display: flex;
		align-items: center;
		padding: 0 30rpx;
		color: #fff;

		.contentText {
			font-size: 32rpx;
			margin-left: 2rpx;
			font-weight: bold;
		}
	}

</style>